<?php

/**
 * Description of SBVariantsList
 *
 * @author tonatos
 */
class SBVariant {

    public $id;
    public $id_product;
    public $name;
    public $price;
    public $article;
    public $image;
    public $description;
    public $hide;
    protected $table;

    public function __construct($data=null) {
        global $modx;
        $this->table = $modx->getFullTableName("sbshop_product_variants");

        //Передали данные для инициализации
        if ($data != null) {

            //Массив - берем данные оттуда
            if (is_array($data)) {
                $this->data($data);
            }

            //Число - идентификатор, подгружаем из базы
            if (is_numeric($data)) {
                $this->load($data);
            }
        }
    }

    public function data($data) {
        foreach ($data as $key => $value) {
            //if (property_exists($this,$key)){
            $this->$key = $value;
            //}
        }

        $this->hide = !empty($data['hide']) ? 1 : 0;
    }

    public function load($id) {
        global $modx;

        $id = (int) $id;
        if (empty($id))
            return false;

        $rs = $modx->db->query("select * from $this->table where id=$id");
        if (!$rs)
            return false;

        $data = $modx->db->GetRow($rs);
        if (!$data)
            return false;

        $this->data($data);

        return true;
    }

    public function show($index=0) {
        include(MODX_BASE_PATH . "assets/extends/sbshop/modules/templates/variant.show.tpl");
    }

    public function save() {
        global $modx;

        $data = array();
        $data['name'] = $modx->db->escape($this->name);
        $data['article'] = $modx->db->escape($this->article);
        $data['price'] = $modx->db->escape($this->price);
        $data['description'] = $modx->db->escape($this->description);
        $data['id_product'] = (int) $this->id_product;
        $data['hide'] = (int) $this->hide;

        if (!empty($this->image_src)){


            //Сохраняем изображение
            if(is_uploaded_file($this->image_src)) {
                    /**
                     * Определяем базовую директорию для изображений
                     */
                    $sBasePath = $modx->sbshop->config['image_base_dir'] . $this->id_product . '/options/';

                    /**
                     * НЕ Делаем ресайз, сохраняем оригинал файла
                     */
                    if(!is_dir($sBasePath)) {
                        mkdir($sBasePath, 0777, true);
                    }

                    //генерим уникальное имя
                    $new_image_name = md5(uniqid(rand(),true));
                    move_uploaded_file($this->image_src, $sBasePath.$new_image_name.".jpg");

                    if (!empty($this->image)){
                        //Удаляем старый файл
                        unlink($sBasePath.$this->image);
                    }

                    $data['image']=$new_image_name.".jpg";
            }
            
        }
        
        //новый
        if (empty($this->id)) {
            $this->id = $modx->db->insert($data, $this->table);
        } else {
            $modx->db->update($data, $this->table, "id=$this->id");
        }
    }

    public function delete() {
        global $modx;

        //Удалить файл
        if (!empty($this->image)){
            $filename  = $modx->sbshop->config['image_base_dir'] . $this->id_product . '/options/'.$this->image;
            if (file_exists($filename)){
                unlink($filename);
            }
        }
        
        
        $modx->db->delete($this->table, "id=$this->id");
    }

}

class SBVariantsList {

    /*
     * Список вариантов     
     */
    protected $list;
    public $id_product;

    public function __construct() {
        global $modx;
        $this->table = $modx->getFullTableName("sbshop_product_variants");
    }

    public function load($id_product) {
        global $modx;
        $id_product = (int) $id_product;
        if (empty($id_product))
            return;

        $list = $modx->getIntTableRows("*", "sbshop_product_variants", "id_product=$id_product");

        $this->list = array();

        foreach ($list as $row) {
            $this->list[] = new SBVariant($row);
        }
    }

    public function replace($data) {
        $this->load($this->id_product);

        foreach ($data as $index => $row) {

            if ($_FILES['variants']['size'][$index]['image_src'] > 0) {
                //Подгружаем картинку
                $row['image_src'] = $_FILES['variants']['tmp_name'][$index]['image_src'];
            }

            //Добавляем новый
            if (empty($row[id])) {

                $par = new SBVariant($row);
                $par->is_new = true;
                $par->no_delete = true;
                $par->id_product = $this->id_product;

                $this->list[] = $par;

                //заменяем остальные
            } else {
                //Ищем по id (изменения)
                foreach ($this->list as $key => $value) {
                    if ($value->id == $row['id']) {

                        $this->list[$key]->data($row);
                        $this->list[$key]->no_delete = true;
                    }
                }
            }
        }

        foreach ($this->list as $row) {
            if ($row->no_delete) {
                $row->save();
            } else {
                $row->delete();
            }
        }
    }

    public function show() {
        $index = 0;
        $data="";
        if ($this->list){
            ob_start();
            foreach ($this->list as $row) {
                $row->show($index++);
            }
            $data = ob_get_contents();
            ob_end_clean();
        }
        return $data;
    }

    public function show_front() {
        global $modx;
        $sTemplate = $modx->sbshop->getSnippetTemplate('product');

        list($sProduct, $sAbsentProduct, $sOuterTmb, $sRowTmb, $sOuterAttr, $sRowAttr, $sOuterOpts, $sOuterOpt, $sRowSimpleOpt, $sRowMultOpt, $sOuterBundl, $sRowBundl, $sOuterBundlOpt, $sRowBundlOpt, $sVariantsOuter, $sVariantsRow) = explode('<!-- ### -->', $sTemplate);


        $keys = array();
        $keys[] = "[+id+]";
        $keys[] = "[+name+]";
        $keys[] = "[+price+]";
        $keys[] = "[+article+]";
        $keys[] = "[+description+]";
        $keys[] = "[+image+]";


        $result = "";
        foreach ($this->list as $row) {

            if ($row->hide)
                continue;

            $values = array();
            $values[] = $row->id;
            $values[] = $row->name;
            $values[] = $row->price;
            $values[] = $row->article;
            $values[] = $row->description;

            if (!empty($row->image)){
                $values[] = "<img src='/thumb.php?id_options=$row->id&type=small' />";
            }else{
                $values[] = "";
            }


            $result.=str_replace($keys, $values, $sVariantsRow);
        }

        return $result;
    }

}

?>
